/*
 * Wantmore - Service Delivery Platform.
 *
 * $Id: ImageAddFormController.java 60 2010-10-13 07:26:24Z alexey.batyuta@gmail.com $
 *
 * Copyright 2010 by Sunbay Software Crimea Ltd.
 * All rights reserved
 */
package ua.crimea.bat.ss.forms;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import ua.crimea.bat.ss.model.beans.Album;
import ua.crimea.bat.ss.model.beans.Image;
import ua.crimea.bat.ss.services.PhotoAlbumsService;

import java.io.IOException;

/**
 * User: bat
 * Date: Mar 26, 2010
 * Time: 9:21:36 AM
 */
@Controller("imageAddFormController")
@RequestMapping("/albums/{albumId}/images/new")
@SessionAttributes("image")
public class ImageAddFormController {
    protected PhotoAlbumsService photoAlbumsService;
    protected Image image;

    public ImageAddFormController() {
    }

    public void setPhotoAlbumsService(PhotoAlbumsService photoAlbumsService) {
        this.photoAlbumsService = photoAlbumsService;
    }

    public PhotoAlbumsService getPhotoAlbumsService() {
        return photoAlbumsService;
    }

    @InitBinder
    public void setAllowedFields(WebDataBinder dataBinder) {
        dataBinder.setDisallowedFields("id", "image", "thumb");
    }

    @Autowired
    public ImageAddFormController(PhotoAlbumsService photoAlbumsService) {
        setPhotoAlbumsService(photoAlbumsService);
    }

    @RequestMapping(method = RequestMethod.GET)
    public String setupForm(@PathVariable("albumId") int albumId, Model model) {
        Album album = photoAlbumsService.loadAlbum(albumId);
        image = new Image();
        album.addImage(image);
        model.addAttribute("image", image);
        return "images/form";
    }

    @RequestMapping(method = RequestMethod.POST)
    public String processSubmit(@RequestParam("name1") String name, @RequestParam("image1") MultipartFile imageBlob, @RequestParam("thumb1") MultipartFile thumbBlob) {
        //Image image = new Image();
        image.setName(name);
        if (!imageBlob.isEmpty()) {
            try {
                byte[] bytes = imageBlob.getBytes();
                image.setImage(bytes);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (!thumbBlob.isEmpty()) {
            try {
                byte[] bytes = thumbBlob.getBytes();
                image.setThumb(bytes);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


        photoAlbumsService.storeImage(image);
        return "redirect:/albums/" + image.getAlbum().getId();

    }
}
